package yto.freemarker.springbootstudy.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 下载
 *
 * @author dongxing
 * @create 2018-03-21 18:53
 **/
@RestController
@RequestMapping("/resource")
@Slf4j
public class FileDownloadController {

    /**
     * 和fastJson冲突，如果项目中用了FastJson，请选择第二种下载方式(最好选用第二种下载方式，第一种有坑,打成jar，获取文件的路径有问题！)
     *
     * @param pluginName
     * @return
     */
    @GetMapping("/{pluginName}")
    public ResponseEntity<InputStreamResource> downLoad(@PathVariable String pluginName) {

        try {

//            String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();

            FileSystemResource file = new FileSystemResource(ResourceUtils.getURL("classpath:").getPath() + "static/plugin/" + pluginName);

            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");

            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.contentLength())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(file.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件下载失败,失败的原因为：" + e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }

    }


    /**
     * 通用的下载方式,基于文件的file形式
     *
     * @param id
     * @param request
     * @param response
     * @throws FileNotFoundException
     */
    @GetMapping("/1/2")
    public void getDownload(Long id, HttpServletRequest request, HttpServletResponse response) {

        try {


            InputStream stream = this.getClass().getClassLoader().getResourceAsStream("static/plugin/a.txt");
            File downloadFile = new File("a.txt");
            FileUtils.copyInputStreamToFile(stream, downloadFile);

            // Get your file stream from wherever.

            ServletContext context = request.getServletContext();

            // get MIME type of the file
            String mimeType = context.getMimeType("a.txt");
            if (mimeType == null) {
                // set to binary type if MIME mapping not found
                mimeType = "application/octet-stream";
                System.out.println("context getMimeType is null");
            }
            System.out.println("MIME type: " + mimeType);

            // set content attributes for the response
            response.setContentType(mimeType);
            response.setContentLength((int) downloadFile.length());

            // set headers for the response
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"",
                    downloadFile.getName());
            response.setHeader(headerKey, headerValue);

            // Copy the stream to the response's output stream.

            InputStream myStream = new FileInputStream(downloadFile);
            IOUtils.copy(myStream, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件下载失败！" + e);
        }
    }
}
